<?php

namespace app\index\controller;

use app\BaseController;
use app\model\Code;
use extend\Mail;
use extend\SmsExt;

/*
 * 短信类
 */

class Sms extends BaseController
{
    /**
     * 发送短信/邮件
     */
    public function send(): \think\response\Json
    {
        $user = request()->post("phone", false);
        $type = check_account_type($user);
        if ($type === 'mobile') {
            return $this->sendMobile($user);
        }
        if ($type === 'mail') {
            return $this->sendEmail($user);
        }
        return $this->error('请输入账号');
    }

    //发送短信
    private function sendMobile($phone): \think\response\Json
    {
        $phone = strval($phone); //转换成字符串
        if (!isMobile($phone)) {
            return $this->error('手机号码不符合规范');
        }
        if (Code::where("user", $phone)->where('create_time', ">", (time() - 60))->order("create_time", "desc")->find()) {
            return $this->error('发送频繁,请稍后再试');
        }
        $code = rand(1000, 9999);
        (new \app\model\Code)->insert(["user" => $phone, "code" => $code, "create_time" => time(), "status" => 1]);
        $template = "【载涂图床】您正在操作登录账号，您的验证码为{$code}，有效期10分钟，如非本人操作请勿泄露！";
        $result_send = SmsExt::send($phone, $template);
        if ($result_send) {
            return $this->success("发送成功");
        }
        return $this->error("发送失败");
    }

    /**
     * 获取邮箱验证码
     */
    private function sendEmail($email): \think\response\Json
    {
        if (empty($email)) {
            return $this->error("请提交邮箱");
        }
        $code = rand(1000, 9999);
        if (Code::where('user', $email)->where('create_time', '>', (time() - 60))->order('create_time', 'desc')->find()) {
            return $this->error('发送频繁,请稍后再试');
        }
        $result = Code::insert(["user" => $email, "code" => $code, "create_time" => time(), "status" => 1]);
        if ($result) {
            $suc = Mail::send($email, $code);
            if ($suc) {
                return $this->success("发送成功");
            }
        }
        return $this->error("发送失败");
    }

    /**
     * @description: 验证码验证
     * @param {*} $mobile 手机号
     * @param {*} $code 验证码
     * @return {*}
     */
    public static function codeCheck($mobile, $code)
    {
        return Code::where("user", $mobile)->where("code", $code)->where("status", 1)->find();
    }

    /**
     * @description: 销毁验证码
     * @param {*} $mobile 手机号
     * @param {*} $code 验证码
     * @return {*}
     */
    public static function codeDestroy($mobile, $code)
    {
        return Code::where("user", $mobile)->where("code", $code)->update(['status' => 2]);
    }
}
